<!DOCTYPE html>
<html lang="en">
<meta name="format-detection" content="telephone=no" />
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="../../css/mui.min.css">
<link rel="stylesheet" href="../../css/base.css">
<script src="../../script/api.js" type="text/javascript"></script>
<script src="../../script/jquery.min.js" type="text/javascript"></script>
<!--<script src="../../script/MD5.js"></script>-->
<script type="text/javascript" src="../../script/requestTool.js"></script>
<script src="../../script/ui.js"></script>
<style>
    .msg_red {
        height: 20px;
        width: 20px;
        position: absolute;
        right: 0;
        text-align: center;
        background: red;
        color: white;
        font-size: 7px;
        line-height: 20px;
        border: 1px solid red;
        border-radius: 15px;
    }

    .formeTag:before {
        content: "[有人@我] ";
        color: red;
    }

    .msg_content {
        width: 60%;
        padding-top: 5px;
        padding-left: 10px;
        color: rgb(51, 51, 51);
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }

    .tab {
        margin-top: 10px;
        margin-left: 10px;
    }

    .add_group {
        width: 30px;
        height: 30px;
        border: 1px solid #eeeeee;
        font-size: 30px;
        border-radius: 15px;
        padding: 0;
        display: none;
    }

    .mui-pull-left img {
        width: 40px;
    }

    .none_msg {
        width: 100%;
        background: white;
        padding: 10px;
    }

    .centerBar {
        width: 80%;
        position: absolute;
        left: 50%;
        transform: translate(-50%, 0);
        line-height: 44px;
        box-sizing: border-box;
    }

    .centerBar div {
        /*width: 100%;*/
        margin-right: 2rem;
        vertical-align: bottom;
        background: transparent;
        padding-bottom: 10px;
        line-height: 1;
        display: inline-block;
    }


    .centerBar_unSelect {
        color: white;
        border-radius: 0;
        border: 0;
        border-bottom: 2px solid transparent;
    }

    .centerBar_btnSelect {
        color: rgb(231, 84, 90);
        border-radius: 0;
        border: 0;
        border-bottom: 2px solid rgb(231, 84, 90);

    }

    .my-ring .other-ring {
        position: relative;
    }
</style>
<body>
<div id='BarAppearance'></div>
<div class="base_navigation_bar base_style_color">
    <a class="base_left_item" href="#" onclick="backClick()"> <img class="base_back_icon"
                                                                   src="../../image/icon_jiantou.png" alt=""> </a>
    <div class="centerBar" style="text-align: center;">
        <div onclick="myRing()">我的圈子</div>
        <div onclick="otherRing()">更多圈子</div>
    </div>
</div>
<div id="my-ring">
    <div id="myFail" style="display: none; position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%)">
        <img src="../../image/conn_fail.png">
        <div style="margin-top: 20px;text-align:center;">加载失败</div>
    </div>
</div>
<div id="other-ring">
    <div id="oterfail" style="display: none; position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%)">
        <img src="../../image/conn_fail.png">
        <div style="margin-top: 20px;text-align:center;">加载失败</div>
    </div>
</div>
</body>
</html>
<script>

</script>
<script>
    var mode;
    var easeChat;
    var page = 1;
    var ringMap = new Map();
    apiready = function () {
        easeChat = api.require('easeChat');
        initHeaderUI();
        // initData();
        loginHuanxing();
        myRing();//切换至我的圈子
    };

    function myRing() {
        mode = "mine";
        $('#my-ring').show();
        $('#other-ring').hide();
        $('.centerBar div:eq(0)').removeClass().addClass('centerBar_btnSelect');
        $('.centerBar div:eq(1)').removeClass().addClass('centerBar_unSelect');
    }

    function otherRing() {
        mode = "other";
        $('#my-ring').hide();
        $('#other-ring').show();
        $('.centerBar div:eq(0)').removeClass().addClass('centerBar_unSelect');
        $('.centerBar div:eq(1)').removeClass().addClass('centerBar_btnSelect');
    }

    function register() {
        //关闭消息推送
        if(api.systemType==='ios'){
            easeChat.setLocalNotification({
                enable: false,
                title: '您有一条新的消息'
            });
        }

        //注册消息监听
        easeChat.addAccountListener(function (ret) {
            console.log("账号异常登录");
            api.alert({msg: "您的账号在其他位置登录"});
            api.closeToWin({
                name: 'index'
            });
        });
        //todo 环信消息接收监听
        easeChat.addMessageListener({
            name: 'receive'
        }, function (ret) {
            console.log("收到消息:" + JSON.stringify(ret));
            setRingCurrentInfo(ret.messages[ret.messages.length - 1]);//设置最后一条消息
            for (var i = 0; i < ret.messages.length; i++) {
                var message = ret.messages[i];
                var num = ringMap.get("id_" + message.conversationId);
                num++;
                ringMap.set("id_" + message.conversationId, num);
                converMark(message.conversationId, num);
            }
            api.sendEvent({
                name: 'ringmessage',
                extra: {
                    message: ret.messages,
                }
            });
        });

        api.addEventListener({
            name: 'scrolltobottom'
        }, function (ret, err) {
            if (mode === "other")
                getOtherRingInfo();
        });
        //todo 已读消息更新
        api.addEventListener({
            name: 'ringMarkMessage'
        }, function (ret, err) {
            var conversationId = ret.value.conversationId;
            var num = ringMap.get("id_" + ret.value.conversationId);
            num = Math.max(0, num - ret.value.num);
            ringMap.set("id_" + conversationId, num);
            $('#ring_' + conversationId).find("p").removeClass('formeTag');
            converMark(conversationId, num);
        });
        api.addEventListener({
            name: 'message'
        }, function (ret, err) {
            console.log(JSON.stringify(ret.value.message));
            setRingCurrentInfo(ret.value.message);//设置最后一条消息
        });
    }

    function initData() {
        cfnetppPOST(url_ring_mine,{"uid":$api.getStorage('cfnetppuid')}, false, function (data, status) {
            if (data.status) {
                if (data.data.list.length === 0) {
                    $('#myFail').show();
                    $('#myFail div').text("您还未加入圈子");
                    return;
                }
                for (var i = 0; i < data.data.list.length; i++) {
                    var item = data.data.list[i];
                    $('#my-ring').append(addmineItem(item.group_id, item.group_image, item.group_name, item.effective_state));
                    ringMap.set("id_" + item.group_id, 0);
                    if (!item.mention_flag) {
                        $('#ring_' + item.group_id).find("p").addClass('formeTag');
                    }
                    ringMap.set("id_" + item.group_id, item.unread_msg_num);//初始化未读数1
                    if (item.last_msg)
                        setRingCurrentInfo(item.last_msg);
                    converMark(item.group_id, item.unread_msg_num);
                }
            } else {
                $('#myFail').show();
                $('#myFail div').text("加载失败");
            }
        });
        getOtherRingInfo();
    }

    /**
     * 获取公共圈子信息
     * */
    function getOtherRingInfo() {
        cfnetppPOST(url_ring_other,{
            "page":page,
            "uid": $api.getStorage('cfnetppuid'),
            "rows":10
        } , false, function (data, status) {
            if (data.status) {
                if (data.data.list.length === 0) {
                    $('#otherFail').show();
                    $('#otherFail div').text("暂无数据");
                }
                for (var i = 0; i < data.data.list.length; i++) {
                    var item = data.data.list[i];
                    $('#other-ring').append(addOtherItem(item.group_id, item.group_image, item.group_name, item.affiliations_count, item.msg_count));
                }
                page++;
            } else {
                $('#otherFail').show();
                $('#otherFail div').text("加载错误");
            }
        })
    }

    //获取会话信息
    function getConversation(conversationId) {
        easeChat.getConversation({
            conversationId: conversationId,
            type: 'groupChat',
            ifCreate: false
        }, function (ret) {
            if (ret.status) {
                console.log("回话消息:" + JSON.stringify((ret.conversation.latestMessage)));
            }
        });
    }

    /**
     * 更新圈子最新消息
     * @param message 消息体
     */
    function setRingCurrentInfo(message) {
        var show;
        switch (message.body.type) {
            case "text"://文本
                if (message.ext) {
                    if (isAtme(message) && !message.isRead) {
                        $('#ring_' + message.conversationId).find("p").addClass('formeTag');
                    }
                }
                show = parseEmoji(message.body.text.replace('</br>', ''));
                break;
            case "image"://图片s
                show = "[图片]";
                break;//text：文本类型
            case "voice"://语音
                show = "[语音]";
                break;
            case "video"://视频
                show = "[视频]";
                break;
            case "file"://文件
                show = "[文件]";
                break;

        }
        $('#ring_' + message.conversationId).find("p").html(show);
        var date = timestampToTime(message.timestamp);
        $('#ring_' + message.conversationId).find(".mui-badge").text(date);
    }

    function isAtme(message) {
        if (!message.ext.at)
            return false;
        var atList = message.ext.at;
        if (!(atList instanceof Object))
            atList = JSON.parse(atList);
        if (atList) {
            for (var i = 0; i < atList.length; i++) {
                if (atList[i].userId+"" === $api.getStorage('cfRingUsername')) {
                    return true;
                }
                if (atList[i].userId === "all" && message.from !== $api.getStorage('cfRingUsername'))
                    return true;
            }
        }
        return false;
    }

    function converMark(conversationId, num) {
        if (num >= 100) {
            $('#ring_' + conversationId).find('.msg_red').show();
            $('#ring_' + conversationId).find('.msg_red').html("100+");
        } else if (num > 0 && num < 100) {
            $('#ring_' + conversationId).find('.msg_red').show();
            $('#ring_' + conversationId).find('.msg_red').html(num);
        } else {
            $('#ring_' + conversationId).find('.msg_red').hide();
        }
    }

    /**
     * 我的圈子列表
     * @param id 圈子id
     * @param name 圈子名字
     * @param image 圈子头像
     * @param effective_state 是否过期
     * @returns {string} item
     */
    function addmineItem(id, image, name, effective_state) {
        return " <ul id='ring_" + id + "' class=\"mui-table-view\" onclick=\"groupDetail('" + id + "','" + name + "'," + effective_state + ")\">\n" +
            "        <li class=\"mui-table-view-cell mui-media\">\n" +
            "            <div class=\"mui-pull-left\" style=\"position: relative;\">\n" +
            "                <span class=\"msg_red\" style='display: none'>100+</span>\n" +
            "                <img src='" + image + "'>\n" +
            "            </div>\n" +
            "            <div class=\"mui-media-body msg_content\">\n" + name +
            "                <p class='mui-ellipsis'></p>\n" +
            "            </div>\n" +
            "            <div class=\"mui-badge\" style=\"background: transparent\">" + (effective_state ? '' : '已过期') + "</div>\n" +
            "        </li>\n" +
            "    </ul>"
    }

    /**
     * 公共圈子列表
     * @param id 圈子id
     * @param name 名字
     * @returns {string}  item
     */
    function addOtherItem(id, image, name, count, msg_count) {
        return "<ul id='ring_" + id + "' class=\"mui-table-view\">\n" +
            "    <li class=\"mui-table-view-cell mui-media\">\n" +
            "        <div class=\"mui-pull-left\" style=\"position: relative;\">\n" +
            "\n" +
            "            <img src='" + image + "'>\n" +
            "        </div>\n" +
            "\n" +
            "        <div class=\"mui-media-body msg_content\" style='padding-top: 0'>\n" + name +
            "            <div style='margin-top: .3rem'><div ><img style='float: left;width: 1rem;height: 1rem' src='../../image/chat/chat_people.png'/><p style='margin-left:.2rem;height:1rem;line-height:1rem;float: left' class='mui-ellipsis'>" + count + "</p></div>" +
            "                 <div style='margin-left: 4rem'><img style='float: left;width: 1rem;height: 1rem' src='../../image/chat/chat_speak.png'/><p style='margin-left:.2rem;height:1rem;line-height:1rem;float: left' class='mui-ellipsis'>" + (msg_count >= 1000 ? parseInt(msg_count / 1000) + "k" : msg_count) + "</p></div></div>\n" +
            "        </div>\n" +
            "\n" +
            "        <Button class=\"mui-badge add_group\" style=\"background: transparent\">+</Button>\n" +
            "    </li>\n" +
            "</ul>";
    }

    function backClick() {
        console.log("dsadas");
        api.closeWin();
    }

    function groupDetail(id, name, effective_state) {
        api.openWin({useWKWebView:true,
            name: 'groupDetail',
            url: 'groupDetail.html',
            pageParam: {
                conversationId: id,
                conversationName: name,
                effective_state: effective_state
            }
        });
    }

</script>
<script>
    var WebIM = {};
    WebIM.Emoji = {
        path: '../../image/chat/emoji/',
        map: {
            '[:A)]': 'aini.png',
            '[:B)]': 'bishi.png',
            '[:C)]': 'bizui.png',
            '[:D)]': 'bulini.png',
            '[:E)]': 'daku.png',
            '[:F)]': 'deyi.png',
            '[:G)]': 'gaxiao.png',
            '[:H)]': 'jiaxiao.png',
            '[:I)]': 'kaixin.png',
            '[:J)]': 'keai.png',
            '[:K)]': 'liuhan.png',
            '[:L)]': 'liuhan_1.png',
            '[:M)]': 'nanguo.png',
            '[:N)]': 'nanshou.png',
            '[:O)]': 'se.png',
            '[:P)]': 'weixiao.png',
            '[:Q)]': 'xiaoku.png',
            '[:R)]': 'xiudaliao.png',
            '[:S)]': 'yukuai.png',
            '[:T)]': 'zhiqi.png',
        }
    };

    function parseEmoji(e) {
        if (void 0 === WebIM.Emoji || void 0 === WebIM.Emoji.map) return e;
        var t = WebIM.Emoji;
        for (var r in t.map) if (t.map.hasOwnProperty(r)) for (; e.indexOf(r) > -1;) e = e.replace(r, '<img class="emoji" style="vertical-align:text-bottom;border: none;width: 16px;height: 16px" src="' + t.path + t.map[r] + '" />');
        return e
    }

</script>
<script>
    function timestampToTime(timestamp) {
        if ((timestamp + "").length <= 10)
            timestamp *= 1000;
        var date = new Date(timestamp);
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        D = date.getDate();
        h = date.getHours() + ':';
        m = date.getMinutes();
        s = date.getSeconds();
        var currentDate = new Date();
        var currentM = (currentDate.getMonth() + 1 < 10 ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1);
        var currentD = currentDate.getDate();
        var showTime = '';
        if (currentM !== M || currentD !== D) {
            showTime = M + "月" + D + '日 ';
        }
        if ((h + "").length === 2) {
            h = "0" + h;
        }
        if ((m + "").length === 1) {
            m = "0" + m;
        }
        return showTime + h + m;
    }
</script>
<script>
    function loginHuanxing() {
        var easeChat = api.require('easeChat');
        easeChat.login({
            username: $api.getStorage('cfRingUsername'),
            password: $api.getStorage('cfRingPassword'),
            autoLogin: true
        }, function (ret, err) {
            // initData();
            console.log("环信登录结果:" + JSON.stringify(ret)+","+JSON.stringify(err));
            if (ret.status) {
                register();
                initData();
            } else {
                api.toast({msg: "消息登录失败"});
            }
        });
    }
</script>